package com.fucheng.server;

import com.fucheng.common.RpcRequest;
import com.fucheng.common.RpcResponse;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * 处理任务交给线程池执行，主线程只负责接收
 */
public class RpcRequestHandler implements Runnable{

    private final Socket socket;

    public RpcRequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try(ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())){

            // 反序列化请求对象
            RpcRequest rpcRequest = (RpcRequest) ois.readObject();

            // 按 serviceName + version 获取服务配置
            ServiceConfig<?> serviceConfig = ServerRegistry.getService(rpcRequest.getServiceName(), rpcRequest.getVersion());
            Object service = serviceConfig.getRef();

            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamsTypes());
            Object result = method.invoke(service, rpcRequest.getParams());

            // 构造响应并返回
            RpcResponse rpcResponse = new RpcResponse();
            rpcResponse.setData(result);
            rpcResponse.setMessage("success");

            oos.writeObject(rpcResponse);

//            ois.close();
//            oos.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
